//
//  CZTabBar.swift
//  Blog
//
//  Created by whitcast on 16/7/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//设置代理
protocol CZTabBarDelegate: NSObjectProtocol {
    func didSelectedComposeButton()
}

class CZTabBar: UITabBar {
    //点击的闭包
    var composeButtonClosure: (()->())?
    
    //定义代理对象
     weak var czDelegate: CZTabBarDelegate?
    
    // MARK: -- 懒加载控件
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        // 添加点击事件
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside)
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        button.sizeToFit()
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(composeButton)
    }
    //加载xib和storyBoard才会调用
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -- 点击事件
    
    @objc private func composeButtonAction() {
        print("afads")
        //调用闭包
        composeButtonClosure?()
        //调用代理
        czDelegate?.didSelectedComposeButton()
        
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置按钮的在中心点
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        
        // 计算控件的宽度
        let itemWidth = width / 5
        //记录遍历是第一个按钮
        var index = 0
        for value in subviews{
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                value.x = CGFloat(index) * itemWidth
                value.width = itemWidth
                if index == 1 {
                    index++
                }
                index++
            }
        }
        
    }
    
   
}
